//package com.rongji.cms.tools.flowable.service.impl;/**
// * @author yang
// * @date 2022/9/20 14:41
// * @description
// */
//
//import cn.hutool.core.collection.CollUtil;
//import cn.hutool.core.date.BetweenFormatter;
//import cn.hutool.core.date.DateUtil;
//import cn.hutool.core.util.ObjectUtil;
//import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
//import com.rongji.cms.tools.common.core.domain.PageQuery;
//import com.rongji.cms.tools.common.core.page.TableDataInfo;
//import com.rongji.cms.tools.common.exception.ServiceException;
//import com.rongji.cms.tools.common.utils.StringUtils;
//import com.rongji.cms.tools.flowable.constant.TaskConstants;
//import com.rongji.cms.tools.flowable.domain.vo.WfDefinitionVo;
//import com.rongji.cms.tools.flowable.domain.vo.WfDetailVo;
//import com.rongji.cms.tools.flowable.domain.vo.WfTaskVo;
//import com.rongji.cms.tools.flowable.factory.FlowServiceFactory;
//import com.rongji.cms.tools.flowable.service.IWfProcessService;
//import com.rongji.cms.tools.flowable.service.IWfTaskService;
//import com.rongji.cms.tools.flowable.utils.TaskUtils;
//import lombok.RequiredArgsConstructor;
//import org.flowable.engine.history.HistoricProcessInstance;
//import org.flowable.engine.repository.Deployment;
//import org.flowable.engine.repository.ProcessDefinition;
//import org.flowable.engine.repository.ProcessDefinitionQuery;
//import org.flowable.engine.runtime.ProcessInstance;
//import org.flowable.engine.task.Comment;
//import org.flowable.identitylink.api.history.HistoricIdentityLink;
//import org.flowable.task.api.Task;
//import org.flowable.task.api.TaskQuery;
//import org.flowable.task.api.history.HistoricTaskInstance;
//import org.flowable.task.api.history.HistoricTaskInstanceQuery;
//import org.springframework.stereotype.Service;
//import org.springframework.transaction.annotation.Transactional;
//
//import java.util.ArrayList;
//import java.util.List;
//import java.util.Map;
//import java.util.Objects;
//
///**
// * @author yang
// * @date 2022/9/20 14:41
// * @description
// */
//@Deprecated
//@RequiredArgsConstructor
//@Service
//public class WfProcessServiceImpl extends FlowServiceFactory implements IWfProcessService {
//
//    private final IWfTaskService wfTaskService;
//
//
//    /**
//     * 流程定义列表
//     *
//     * @param pageQuery 分页参数
//     * @return 流程定义分页列表数据
//     */
//    @Override
//    public TableDataInfo<WfDefinitionVo> processList(PageQuery pageQuery) {
//        Page<WfDefinitionVo> page = new Page<>();
//        // 流程定义列表数据查询
//        ProcessDefinitionQuery processDefinitionQuery = repositoryService.createProcessDefinitionQuery()
//                .latestVersion()
//                .active()
//                .orderByProcessDefinitionKey()
//                .asc();
//        long pageTotal = processDefinitionQuery.count();
//        if (pageTotal <= 0) {
//            return TableDataInfo.build();
//        }
//        int offset = pageQuery.getPageSize() * (pageQuery.getPageNum() - 1);
//        List<ProcessDefinition> definitionList = processDefinitionQuery.listPage(offset, pageQuery.getPageSize());
//
//        List<WfDefinitionVo> definitionVoList = new ArrayList<>();
//        for (ProcessDefinition processDefinition : definitionList) {
//            String deploymentId = processDefinition.getDeploymentId();
//            Deployment deployment = repositoryService.createDeploymentQuery().deploymentId(deploymentId).singleResult();
//            WfDefinitionVo vo = new WfDefinitionVo();
//            vo.setDefinitionId(processDefinition.getId());
//            vo.setProcessKey(processDefinition.getKey());
//            vo.setProcessName(processDefinition.getName());
//            vo.setVersion(processDefinition.getVersion());
//            vo.setDeploymentId(processDefinition.getDeploymentId());
//            vo.setSuspended(processDefinition.isSuspended());
//            // 流程定义时间
//            vo.setCategory(deployment.getCategory());
//            vo.setDeploymentTime(deployment.getDeploymentTime());
//            definitionVoList.add(vo);
//        }
//        page.setRecords(definitionVoList);
//        page.setTotal(pageTotal);
//        return TableDataInfo.build(page);
//    }
//
//
//    /**
//     * 扩展参数构建
//     *
//     * @param variables 扩展参数
//     */
//    private void buildProcessVariables(Map<String, Object> variables) {
////        String userIdStr = LoginHelper.getUserId().toString();
//        String userIdStr = "";
//        identityService.setAuthenticatedUserId(userIdStr);
//        variables.put(TaskConstants.PROCESS_INITIATOR, userIdStr);
//    }
//
//    /**
//     * 根据流程定义ID启动流程实例
//     *
//     * @param procDefId 流程定义Id
//     * @param variables 流程变量
//     * @return
//     */
//    @Override
//    @Transactional(rollbackFor = Exception.class)
//    public void startProcess(String procDefId, Map<String, Object> variables) {
//        try {
//            ProcessDefinition processDefinition = repositoryService.createProcessDefinitionQuery()
//                    .processDefinitionId(procDefId).singleResult();
//            if (Objects.nonNull(processDefinition) && processDefinition.isSuspended()) {
//                throw new ServiceException("流程已被挂起，请先激活流程");
//            }
//            // 设置流程发起人Id到流程中
//            this.buildProcessVariables(variables);
//            ProcessInstance processInstance = runtimeService.startProcessInstanceById(procDefId, variables);
//            // 给第一步申请人节点设置任务执行人和意见 todo:第一个节点不设置为申请人节点有点问题？
////            wfTaskService.startFirstTask(processInstance, variables);
//        } catch (Exception e) {
//            e.printStackTrace();
//            throw new ServiceException("流程启动错误");
//        }
//    }
//
//
//    /**
//     * 流程详情信息
//     *
//     * @param procInsId 流程实例ID
//     * @param deployId  流程部署ID
//     * @param taskId    任务ID
//     * @return
//     */
//    @Override
//    public WfDetailVo queryProcessDetail(String procInsId, String deployId, String taskId) {
//        WfDetailVo detailVo = new WfDetailVo();
//        HistoricTaskInstance taskIns = historyService.createHistoricTaskInstanceQuery()
//                .taskId(taskId)
//                .includeIdentityLinks()
//                .includeProcessVariables()
//                .includeTaskLocalVariables()
//                .singleResult();
//        if (taskIns == null) {
//            throw new ServiceException("没有可办理的任务！");
//        }
////        detailVo.setTaskFormData(currTaskFormData(deployId, taskIns));
//        detailVo.setHistoryTaskList(historyTaskList(procInsId));
////        detailVo.setProcessFormList(processFormList(procInsId, deployId, taskIns));
//        return detailVo;
//    }
//
//
//    /**
//     * 获取历史任务信息列表
//     */
//    private List<WfTaskVo> historyTaskList(String procInsId) {
//        List<HistoricTaskInstance> taskInstanceList = historyService.createHistoricTaskInstanceQuery()
//                .processInstanceId(procInsId)
//                .orderByHistoricTaskInstanceStartTime().desc()
//                .list();
//        List<Comment> commentList = taskService.getProcessInstanceComments(procInsId);
//        List<WfTaskVo> taskVoList = new ArrayList<>(taskInstanceList.size());
//        taskInstanceList.forEach(taskInstance -> {
//            WfTaskVo taskVo = new WfTaskVo();
//            taskVo.setProcDefId(taskInstance.getProcessDefinitionId());
//            taskVo.setTaskId(taskInstance.getId());
//            taskVo.setTaskDefKey(taskInstance.getTaskDefinitionKey());
//            taskVo.setTaskName(taskInstance.getName());
//            taskVo.setCreateTime(taskInstance.getStartTime());
//            taskVo.setFinishTime(taskInstance.getEndTime());
//            if (StringUtils.isNotBlank(taskInstance.getAssignee())) {
//                /// FIXME: 2022/9/20 人员部门信息后续处理下
////                SysUser user = userService.selectUserById(Long.parseLong(taskInstance.getAssignee()));
////                taskVo.setAssigneeId(user.getUserId());
////                taskVo.setAssigneeName(user.getNickName());
////                taskVo.setDeptName(user.getDept().getDeptName());
//            }
//            // 展示审批人员
//            List<HistoricIdentityLink> linksForTask = historyService.getHistoricIdentityLinksForTask(taskInstance.getId());
//            StringBuilder stringBuilder = new StringBuilder();
//            for (HistoricIdentityLink identityLink : linksForTask) {
//                if ("candidate".equals(identityLink.getType())) {
//                    if (StringUtils.isNotBlank(identityLink.getUserId())) {
////                        SysUser user = userService.selectUserById(Long.parseLong(identityLink.getUserId()));
////                        stringBuilder.append(user.getNickName()).append(",");
//                    }
//                    if (StringUtils.isNotBlank(identityLink.getGroupId())) {
//                        if (identityLink.getGroupId().startsWith(TaskConstants.ROLE_GROUP_PREFIX)) {
//                            Long roleId = Long.parseLong(StringUtils.stripStart(identityLink.getGroupId(), TaskConstants.ROLE_GROUP_PREFIX));
////                            SysRole role = roleService.selectRoleById(roleId);
////                            stringBuilder.append(role.getRoleName()).append(",");
//                        } else if (identityLink.getGroupId().startsWith(TaskConstants.DEPT_GROUP_PREFIX)) {
//                            Long deptId = Long.parseLong(StringUtils.stripStart(identityLink.getGroupId(), TaskConstants.DEPT_GROUP_PREFIX));
////                            SysDept dept = deptService.selectDeptById(deptId);
////                            stringBuilder.append(dept.getDeptName()).append(",");
//                        }
//                    }
//                }
//            }
//            if (StringUtils.isNotBlank(stringBuilder)) {
//                taskVo.setCandidate(stringBuilder.substring(0, stringBuilder.length() - 1));
//            }
//            if (ObjectUtil.isNotNull(taskInstance.getDurationInMillis())) {
//                taskVo.setDuration(DateUtil.formatBetween(taskInstance.getDurationInMillis(), BetweenFormatter.Level.SECOND));
//            }
//            // 获取意见评论内容
//            if (CollUtil.isNotEmpty(commentList)) {
//                List<Comment> comments = new ArrayList<>();
//                for (Comment comment : commentList) {
//                    if (comment.getTaskId().equals(taskInstance.getId())) {
//                        comments.add(comment);
//                    }
//                }
//                taskVo.setCommentList(comments);
//            }
//            taskVoList.add(taskVo);
//        });
//        return taskVoList;
//    }
//
//
//    @Override
//    public TableDataInfo<WfTaskVo> queryPageTodoProcessList(PageQuery pageQuery) {
//        Page<WfTaskVo> page = new Page<>();
//        // FIXME: 2022/9/20 后续处理人员相关的代码
////        Long userId = LoginHelper.getUserId();
//        Long userId = 111L;
//        TaskQuery taskQuery = taskService.createTaskQuery()
//                .active()
//                .includeProcessVariables()
//                .taskCandidateOrAssigned(userId.toString())
//                .taskCandidateGroupIn(TaskUtils.getCandidateGroup())
//                .orderByTaskCreateTime().desc();
//        page.setTotal(taskQuery.count());
//        int offset = pageQuery.getPageSize() * (pageQuery.getPageNum() - 1);
//        List<Task> taskList = taskQuery.listPage(offset, pageQuery.getPageSize());
//        List<WfTaskVo> flowList = new ArrayList<>();
//        for (Task task : taskList) {
//            WfTaskVo flowTask = new WfTaskVo();
//            // 当前流程信息
//            flowTask.setTaskId(task.getId());
//            flowTask.setTaskDefKey(task.getTaskDefinitionKey());
//            flowTask.setCreateTime(task.getCreateTime());
//            flowTask.setProcDefId(task.getProcessDefinitionId());
//            flowTask.setTaskName(task.getName());
//            // 流程定义信息
//            ProcessDefinition pd = repositoryService.createProcessDefinitionQuery()
//                    .processDefinitionId(task.getProcessDefinitionId())
//                    .singleResult();
//            flowTask.setDeployId(pd.getDeploymentId());
//            flowTask.setProcDefName(pd.getName());
//            flowTask.setProcDefVersion(pd.getVersion());
//            flowTask.setProcInsId(task.getProcessInstanceId());
//
//            // 流程发起人信息
//            HistoricProcessInstance historicProcessInstance = historyService.createHistoricProcessInstanceQuery()
//                    .processInstanceId(task.getProcessInstanceId())
//                    .singleResult();
////            SysUser startUser = userService.selectUserById(Long.parseLong(historicProcessInstance.getStartUserId()));
////            flowTask.setStartUserId(startUser.getNickName());
////            flowTask.setStartUserName(startUser.getNickName());
////            flowTask.setStartDeptName(startUser.getDept().getDeptName());
//
//            // 流程变量
//            flowTask.setProcVars(this.getProcessVariables(task.getId()));
//
//            flowList.add(flowTask);
//        }
//        page.setRecords(flowList);
//        return TableDataInfo.build(page);
//    }
//
//    /**
//     * 获取流程变量
//     *
//     * @param taskId 任务ID
//     * @return 流程变量
//     */
//    private Map<String, Object> getProcessVariables(String taskId) {
//        HistoricTaskInstance historicTaskInstance = historyService.createHistoricTaskInstanceQuery()
//                .includeProcessVariables()
//                .finished()
//                .taskId(taskId)
//                .singleResult();
//        if (Objects.nonNull(historicTaskInstance)) {
//            return historicTaskInstance.getProcessVariables();
//        }
//        return taskService.getVariables(taskId);
//    }
//
//
//    @Override
//    public TableDataInfo<WfTaskVo> queryPageFinishedProcessList(PageQuery pageQuery) {
//        Page<WfTaskVo> page = new Page<>();
//        // FIXME: 2022/9/20 后续处理人员相关的代码
////        Long userId = LoginHelper.getUserId();
//        Long userId = 111L;
//        HistoricTaskInstanceQuery taskInstanceQuery = historyService.createHistoricTaskInstanceQuery()
//                .includeProcessVariables()
//                .finished()
//                .taskAssignee(userId.toString())
//                .orderByHistoricTaskInstanceEndTime()
//                .desc();
//        int offset = pageQuery.getPageSize() * (pageQuery.getPageNum() - 1);
//        List<HistoricTaskInstance> historicTaskInstanceList = taskInstanceQuery.listPage(offset, pageQuery.getPageSize());
//        List<WfTaskVo> hisTaskList = new ArrayList<>();
//        for (HistoricTaskInstance histTask : historicTaskInstanceList) {
//            WfTaskVo flowTask = new WfTaskVo();
//            // 当前流程信息
//            flowTask.setTaskId(histTask.getId());
//            // 审批人员信息
//            flowTask.setCreateTime(histTask.getCreateTime());
//            flowTask.setFinishTime(histTask.getEndTime());
//            flowTask.setDuration(DateUtil.formatBetween(histTask.getDurationInMillis(), BetweenFormatter.Level.SECOND));
//            flowTask.setProcDefId(histTask.getProcessDefinitionId());
//            flowTask.setTaskDefKey(histTask.getTaskDefinitionKey());
//            flowTask.setTaskName(histTask.getName());
//
//            // 流程定义信息
//            ProcessDefinition pd = repositoryService.createProcessDefinitionQuery()
//                    .processDefinitionId(histTask.getProcessDefinitionId())
//                    .singleResult();
//            flowTask.setDeployId(pd.getDeploymentId());
//            flowTask.setProcDefName(pd.getName());
//            flowTask.setProcDefVersion(pd.getVersion());
//            flowTask.setProcInsId(histTask.getProcessInstanceId());
//            flowTask.setHisProcInsId(histTask.getProcessInstanceId());
//
//            // 流程发起人信息
//            HistoricProcessInstance historicProcessInstance = historyService.createHistoricProcessInstanceQuery()
//                    .processInstanceId(histTask.getProcessInstanceId())
//                    .singleResult();
////            SysUser startUser = userService.selectUserById(Long.parseLong(historicProcessInstance.getStartUserId()));
////            flowTask.setStartUserId(startUser.getNickName());
////            flowTask.setStartUserName(startUser.getNickName());
////            flowTask.setStartDeptName(startUser.getDept().getDeptName());
//
//            // 流程变量
//            flowTask.setProcVars(this.getProcessVariables(histTask.getId()));
//
//            hisTaskList.add(flowTask);
//        }
//        page.setTotal(taskInstanceQuery.count());
//        page.setRecords(hisTaskList);
////        Map<String, Object> result = new HashMap<>();
////        result.put("result",page);
////        result.put("finished",true);
//        return TableDataInfo.build(page);
//    }
//}
